package cn.tedu.ivos.user.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.dto.UserLoginParam;
import cn.tedu.ivos.user.pojo.dto.UserQuery;
import cn.tedu.ivos.user.pojo.dto.UserSaveParam;
import cn.tedu.ivos.user.pojo.entity.User;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import cn.tedu.ivos.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("开始处理登录业务，参数：{}", userLoginParam);
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());
        if (userVO == null){
            // 用户不存在
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if(!userVO.getPassword().equals(userLoginParam.getPassword())){
            // 密码不正确
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userVO;
    }

    @Override
    public void saveUser(UserSaveParam UserSaveParam) {
        log.debug("开始处理保存用户业务，参数：{}", UserSaveParam);
        User user = new User();
        BeanUtils.copyProperties(UserSaveParam, user);
        if(user.getId() == null){
            user.setPassword("123456");
            user.setCreateTime(new Date());
            log.debug("即将保存用户：{}", user);
            userMapper.insert(user);
        }else {
            user.setUpdateTime(new Date());
            log.debug("即将修改用户：{}", user);
            userMapper.update(user);
        }
    }

    @Override
    public UserVO[] select(UserQuery userQuery) {
        log.debug("开始处理查询用户业务，参数：{}", userQuery);
        UserVO[] userVOS = userMapper.select(userQuery);
        return userVOS;
    }
    @Override
    public void updatePassword(Long userId) {
        log.debug("开始处理修改密码业务，参数：{}", userId);
        User user = new User();
        user.setId(userId);
        user.setPassword("root");
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    public void updateStatus(Long userId, String status) {
        log.debug("开始处理修改状态业务，参数：{},{}", userId, status);
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    public void delete(Long userId) {
        log.debug("开始处理删除用户业务，参数：{}", userId);
        userMapper.delete(userId);
    }
}
